package com.flyqiu.form.extensions.convert.mapping;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.flyqiu.common.tree.FlyQiuTreeTools;

import java.util.HashMap;
import java.util.Map;

public class AvueTreeMapper extends AvueBaseDicDataMapper {
    public static final String MAPPER_TYPE = "tree";

    /**
     * 解析树新数据字典
     *
     * @param array
     * @return
     */
    @Override
    public AvueDicDataMapper analysisDicData(JSONArray array) {
        Map<String, String> labelDic = new HashMap<>();
        Map<String, String> valueDic = new HashMap<>();
        if (array == null || array.isEmpty()) return new AvueDicDataMapper(labelDic, valueDic);
        String labelKey;
        String valueKey;
        String childrenKey = "children";
        if (column.containsKey("props")) {
            JSONObject props = column.getJSONObject("props");
            if (props.containsKey("label")) {
                labelKey = props.getString("label");
            } else {
                labelKey = "label";
            }
            if (props.containsKey("value")) {
                valueKey = props.getString("value");
            } else {
                valueKey = "value";
            }
            if (props.containsKey("children")) {
                childrenKey = props.getString("children");
            }
        } else {
            valueKey = "value";
            labelKey = "label";
        }
        FlyQiuTreeTools.treeToList(array, valueKey, null, childrenKey, null, item -> {
            String label = item.getString(labelKey);
            String value = item.getString(valueKey);
            if (!labelDic.containsKey(label)) {
                labelDic.put(label, value);
            }
            if (!valueDic.containsKey(value)) {
                valueDic.put(value, label);
            }
        });
        return new AvueDicDataMapper(labelDic, valueDic);
    }
}
